import { Component } from 'react'
import { withRouter, Route, Redirect, Switch } from 'react-router-dom'
import { getData } from 'utils/local'
/* 404页面 */
import Error404 from 'pages/Error/404'
@withRouter
class Compile extends Component {
  state = { 
    renderComponent: null
  }

  
  static getDerivedStateFromProps(nextProps) {

      /* 路由列表 */
      const { routes } = nextProps
      /* 获取登录后的标识，没有就是未登录 */
      const hasToken =getData('token')
      /* 存储返回的组件 */
      const storeComponent = (function () {
        function store(routes, action) {
          if (!action) {
            store.components = routes.map( route => (
              <Route 
                key={route.path} 
                path={route.path} 
                component={()=> <route.component routes={route.children} /> }
                exact={route.exact}
              />
            ))
          } else {
            store.components || (store.component = [])
            store.components.push(routes)
          }
        }
        return store
      })()

      /* 用户未登录时返回不需要权限的页面 */
      if (!hasToken) {
        storeComponent(routes.filter( route => !route.auth))
        storeComponent(<Redirect key="redirect" to="/login" />, true)
      } 
      /**
       * 登录后可以访问的页面，判断路由组件的auth是否为true,
       * 如果是true那就添加集合中以待合并到state中
       * 并添加跳转组件访问login页跳转到welcome
       * 添加404页面
       */
      else {
        storeComponent(routes.filter(route => route.auth))
        storeComponent(<Redirect from="/login" to="/" exact key="noLogin" />, true)
        
        if (!routes[0].parentId) {
          storeComponent(<Route component={Error404} key="404" />, true)
        }
      }
    return { renderComponent: storeComponent.components }
  }

  render(){
    return (
      <Switch>
        {this.state.renderComponent}
      </Switch>
    )
  }
}
export default Compile